package com.xbstar.wei.service2;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * 微信公众号设置与个性化相关的类
 * @author jwf
 * @versin 1.0
 * 此类可以做很多的优化
 */
public class APPProperties {
	/**
	 * 此处是做获取access_tocken
	 */
	
	public static String TOKEN="aitianqi1";
	//public static String APPID="wx439c9c70c3815ad0";//wx95b2beb50b72150b
	public static String APPID="wx1823cb77d5bc84c3";
	public static String APPSECRET="f1de040b4e7d8b54ac4e33452befab6d";
	private static String access_token="";
	private static Date oldDate=new Date();
	public Date getLastTime() {
		return oldDate;
	}
	public static String getAccess_token() {
		getLastAccess_token();
		return access_token;
	}
	
	private static void setAccess_token(String access_token) {
		APPProperties.access_token = access_token;
	}
	public static long getExpires_in() {
		return expires_in;
	}
	private static void setExpires_in(long expires_in) {
		APPProperties.expires_in = expires_in;
	}
	private static long expires_in;
	
	
	//https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%%&secret=
	private synchronized static void getLastAccess_token() {
		Date now=new Date();
		long cha=(now.getTime()-oldDate.getTime())/1000;
		//if (true){
		if (access_token.equals("")||expires_in==0||!(cha<expires_in-300)) {//重新获取
			String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
					+APPID+"&secret="+APPSECRET;
			HttpClient client=new DefaultHttpClient();
			
			HttpGet get1=new HttpGet(url);
			JSONObject object=null;
			try {
				HttpResponse response=client.execute(get1);
				
				if (response.getStatusLine().getStatusCode()==HttpStatus.SC_OK ) {
					HttpEntity entity=response.getEntity();
					try {
						String strJ=EntityUtils.toString(entity);
						System.out.println(strJ);
						object= new JSONObject(strJ);
						try {
							access_token=object.getString("access_token");
							expires_in=object.getLong("expires_in");
							oldDate=new Date();
							
						} catch (Exception e) {
							if (object.getInt("errcode")==40013||object.getString("errmsg").equals("invalid appid")) {
								Exception exception=new Exception("appid或者appsecrect出错，请检查");
								exception.printStackTrace();
								client.getConnectionManager().shutdown();
							}
							e.printStackTrace();
							return;
						}
						
						
					} catch (IllegalStateException e) {
						
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					}  
				}else {
					System.out.println("获取accesstocken失败");
					Exception e=new Exception("获取accesstocken失败");
					client.getConnectionManager().shutdown();
					e.printStackTrace();
					return ;	
				}
				
				
			} catch (ClientProtocolException e) {
				
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			finally{
				client.getConnectionManager().shutdown();
			}
		}
		return ;
	}
	//****************获取access_tocken结束************************************//
	/**
	 * 这是设置菜单相关
	 */
	//初始用jsonobject对象表示菜单，但是这种方式适合粗狂式的开发，但是鲁棒性很低
	private static	JSONObject menu=null;
	public static JSONObject getMenu() throws Exception {
		if (menu==null) {
			getMenuFromeWei();
		}
		//getMenuFromeWei();
		
		return menu;
	}
	public static void setMenu(JSONObject obj){
		menu=obj;
		setMenuForWei();
	}
	private static int firstMenuSize=3;
	public static int getFirstMenuSize() {
		return firstMenuSize;
	}
	public static void setFirstMenuSize(int firstMenuSize) {
		APPProperties.firstMenuSize = firstMenuSize;
	}
	public static int getSecondMenuSize() {
		return secondMenuSize;
	}
	public static void setSecondMenuSize(int secondMenuSize) {
		APPProperties.secondMenuSize = secondMenuSize;
	}
	private static int secondMenuSize=5;
	/**
	 * 获取微信菜单
	 * @throws Exception
	 */
	public static void getMenuFromeWei() throws Exception {
		String url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token="+getAccess_token();
		HttpClient client=new DefaultHttpClient();
		HttpGet get=new HttpGet(url);
		JSONObject object=null;
		try {
			HttpResponse response=client.execute(get);
			if (response.getStatusLine().getStatusCode()==HttpStatus.SC_OK ) {
				HttpEntity entity=response.getEntity();
				try {
					String strJ=EntityUtils.toString(entity,"utf-8");
					
//					strJ=URLEncoder.encode(strJ,HTTP.UTF_8);
					//strJ=URLDecoder.decode(strJ,HTTP.UTF_8);
					System.out.println(strJ);
					object= new JSONObject(strJ);
					try {
						
						menu=new JSONObject(object.getString("menu"));
						System.out.println(menu);
					} catch (Exception e) {
						System.out.println("获取菜单失败，请检查appid或者appsecrect");
						try {
							if (object.getInt("errcode")!=-2||!object.getString("errmsg").equals("")) {
								Exception exception=new Exception("appid或者appsecrect出错，请检查");
								exception.printStackTrace();
								client.getConnectionManager().shutdown();
								
							}
						} catch (Exception e2) {
							e2.printStackTrace();
						}
						
					}
					
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("从服务器获取流错误。。。。");
				}
				
				finally{
					client.getConnectionManager().shutdown();
				}
				
				
			}
			
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			System.out.println("协议出错请检查网络配置");
			Exception eeException=new Exception("协议出错请检查网络配置");
			throw eeException;
		
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("io接口出错，请检查网络配置");
			Exception eeException=new Exception("io接口出错，请检查网络配置 ");
			throw eeException;
		}
		return;
		
	}
	/**
	 * 删除菜单
	 */
	private void deleteMenuFromWei(){
		String url="";
	}
	/**
	 * 在微信服务器上设置菜单
	 */
	private static void setMenuForWei() {
		String url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+getAccess_token();
		HttpClient client=new DefaultHttpClient();
		String encoderJson=null;
		try {
			encoderJson = URLEncoder.encode(menu.toString(),HTTP.UTF_8);
		} catch (UnsupportedEncodingException e) {
	
			e.printStackTrace();
			return;
		}
		HttpPost post1=null;
		try {
			 post1=new HttpPost(url);
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		
		StringEntity json;
		try {
			json = new StringEntity(menu.toString(),"UTF-8");
			post1.setEntity(json);
			 try {
				HttpResponse response =client.execute(post1);
				if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK ){
					System.out.println("出错了，可能因为网络原因");
					return;
				}
				String str=EntityUtils.toString(response.getEntity());
				JSONObject object=null;
				try {
					object = new JSONObject(str);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK ) {
					try {
						if(object.getInt("errcode")!=0||!object.getString("errmsg").equals("ok")) {
							Exception exception=new Exception("appid或者appsecrect出错，请检查");
							exception.printStackTrace();
							System.out.println("错误编码："+object.getInt("errcode"));
							client.getConnectionManager().shutdown();	
						}else {
							System.out.println("设置成功");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			} catch (ClientProtocolException e) {
				client.getConnectionManager().shutdown();
				e.printStackTrace();
				
			} catch (IOException e) {
				
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			client.getConnectionManager().shutdown();
		}
		
	}
	@Deprecated
	public static JSONObject send2WeiByGetMethod(String url) throws Exception{
		HttpClient client=new DefaultHttpClient();
		HttpGet get=new HttpGet(url);
		try {
			HttpResponse response=client.execute(get);
			if (response.getStatusLine().getStatusCode()==HttpStatus.SC_OK ) {
				HttpEntity entity=response.getEntity();
				try {
					String str=EntityUtils.toString(entity);
					JSONObject json=new JSONObject(str);
					int num=-1;
					try {
						num=json.getInt("errcode");
					} catch (Exception e) {
						System.out.println("没有errcode这个字段a");
					}
					if (num!=0) {
						client.getConnectionManager().shutdown();	
						throw new Exception("错误编码： "+json.getInt("errcode")+" 错误参考信息： "+json.getString("errmsg"));
					}else {
						return json;			
					}
				} catch (Exception e) {
					client.getConnectionManager().shutdown();	
					System.out.println("获取的不是文件流或者转化成json失败");
					throw new Exception("获取的不是文件流或者转化成json失败");
				}
				
				
			}
			
		} catch (Exception e) {
			client.getConnectionManager().shutdown();	
			System.out.println("网络连接错误");
			throw new Exception("网络连接错误");
		}       
		return null;
	}
	/**
	 * 采用post向微信服务器发送jsonobject对象的方法
	 * @param url 微信连接地址
	 * @obj obj 要发送的对象
	 * @return 返回从服务器中获得值
	 * @throws Exception 
	 */
	@Deprecated
	public static JSONObject send2WeiByPostMethod(String url,JSONObject obj) throws Exception {
		if (obj==null||url==null) {
			return null;
		}
		HttpClient client=new DefaultHttpClient();
		
		//String encoderJson=null;
//		try {
//			encoderJson = URLEncoder.encode(menu.toString(),HTTP.UTF_8);
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//			Exception ee=new Exception("未能对所传对象进行utf8成功编码，可能是所传对象不是jsonobject对象或者有误");
//			throw ee;
//		}
		HttpPost post=new HttpPost(url);
		StringEntity json=new StringEntity(obj.toString(),"UTF-8");
		post.setEntity(json);
		HttpResponse response;
		try {
			 response =client.execute(post);
		} catch (Exception e) {
			Exception ee=new Exception("未能成功上传，可能网络问题，请检查网络后再次尝试！");
			throw ee;
		}
		if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK ) {
			Exception ee=new Exception("网络配置头部有错，请检查确认");
			throw ee;
		}
		String str=EntityUtils.toString(response.getEntity());
		JSONObject object;
		try {
			object = new JSONObject(str);
		} catch (Exception e) {
			Exception ee=new Exception("获取的流转化为json失败");
			throw ee;
		}
		int numF=-1;
		try {
			numF=object.getInt("errcode");
		} catch (Exception e) {
			System.out.println("没有errcode这个字段");
		}
		if (numF!=0) {
			client.getConnectionManager().shutdown();	
			throw new Exception("错误编码： "+object.getInt("errcode")+" 错误参考信息： "+object.getString("errmsg"));
		}else {
			return object;
		}
		
	}
}
